<?php
/**
 * TinyCorePHP 插件相关函数
 * @author 	kelecode@gmail.com
 * @date 		2014-03-09
 */
 
$A = array();

function do_action($tag,$arg=null){
	global $A;
	foreach($A as $action => $func){
		if($action == $tag){
			call_user_func_array('action_'.$action, array($func) );
		}
	}
}

function add_action($tag, $function_to_add){
	global $A;
	$A[$tag][]= $function_to_add;	
}

function action_base($func){
	foreach($func as $callback){
		call_user_func_array( $callback, array() );
	}
}

function get_active_plugin(){
	$table = C('db_table_prefix') . 'options';
	$sql = "SELECT `option_value` FROM `{$table}` WHERE `option_name`='active_plugins'";
	$result = query($sql,'option_value');
	$plugins = empty($result[0]) ? array() : unserialize($result[0]);
	
	return $plugins;
}

function load_plugin($return=false){
	$path = APP_ROOT . '/plugin/*';
	$lists = glob($path);
	if( !is_array($lists) || empty($lists) ){
		return false;
	}
	if($return){
		return $lists;
	}
	$plugin = array();
	$active_plugin = get_active_plugin();
	foreach($lists as $val){
		$basename = basename( $val );
		if( in_array($basename, $active_plugin) ){
			$plugin[] = is_dir($val) ? ($val . '/app.php') : ( is_file($val) ? $val : '' );
		}
	}
	if( !is_array($plugin) || empty($plugin) ){
		return false;
	}
	foreach($plugin as $k => $v){
		if( !empty($v) ){
			require_once($v);
		}
	}
}

//usage:
load_plugin();